<template>
  <div class="class-management">
    <div class="class-management-header">
      <a-tabs v-model:activeKey="activeKey" @change="onTabChange">
        <a-tab-pane key="all" tab="全部" />
        <a-tab-pane key="ongoing" tab="正在进行" />
        <a-tab-pane key="finished" tab="已结束" />
      </a-tabs>
      <a-button type="primary" @click="showCreateClassModal">
        <template #icon>
          <PlusOutlined />
        </template>
        创建班级
      </a-button>
    </div>
    
    <!-- 班级列表 -->
    <div class="class-list" v-loading="loading">
      <a-list
        v-if="filteredClassList.length > 0"
        :data-source="filteredClassList"
        :grid="{ gutter: 16, column: 3 }"
      >
        <template #renderItem="{ item }">
          <a-list-item>
            <a-card hoverable class="class-card">
              <template #title>
                <span class="class-name">{{ item.name }}</span>
              </template>
              <template #extra>
                <a-tag :color="getStatusColor(item.status)">{{ getStatusText(item.status) }}</a-tag>
              </template>
              <p class="class-info">
                <span class="label">班级人数：</span>
                <span>{{ item.studentCount }}人</span>
              </p>
              <p class="class-info">
                <span class="label">邀请码：</span>
                <span class="invite-code">{{ item.inviteCode }}</span>
                <a-button type="link" @click="copyInviteCode(item.inviteCode)">复制</a-button>
              </p>
              <p class="class-info">
                <span class="label">创建时间：</span>
                <span>{{ item.createTime }}</span>
              </p>
              <a-button type="primary" block @click="enterClass(item.id)">
                进入班级
              </a-button>
            </a-card>
          </a-list-item>
        </template>
      </a-list>
      <a-empty v-else description="暂无班级" />
    </div>
    
    <!-- 创建班级模态框 -->
    <a-modal
      v-model:open="createClassModalVisible"
      title="创建新班级"
      @ok="handleCreateClass"
      @cancel="handleCancelCreateClass"
    >
      <a-form :model="createClassForm" layout="vertical">
        <a-form-item
          label="班级名称"
          :rules="[{ required: true, message: '请输入班级名称' }]"
        >
          <a-input v-model:value="createClassForm.name" placeholder="请输入班级名称" />
        </a-form-item>
        <a-form-item label="班级描述">
          <a-textarea v-model:value="createClassForm.description" placeholder="请输入班级描述" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { createClass, getClassList } from '../api/auth.js';


// 活动选项卡
const activeKey = ref('all');

// 创建班级模态框相关
const createClassModalVisible = ref(false);
const createClassForm = reactive({
  name: '',
  description: ''
});

// 模拟班级数据
const classList = ref([]);

// 加载中状态
const loading = ref(false);

// 获取班级列表
const fetchClassList = async () => {
  loading.value = true;
  try {
    const result = await getClassList();
    
    if (result.code === 1 && result.data) {
      // 转换后端数据格式为前端格式
      classList.value = result.data.map(item => ({
        id: item.id,
        name: item.className,
        studentCount: item.total,
        inviteCode: item.accessCode,
        createTime: item.createTime ? item.createTime.split('T')[0] : '',
        description: '',
        status: 'ongoing' // 默认都是进行中
      }));
    } else {
      message.error(result.msg || '获取班级列表失败');
    }
  } catch (error) {
    console.error('获取班级列表失败:', error);
    message.error('获取班级列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 组件挂载时获取班级列表
onMounted(() => {
  fetchClassList();
});

// 根据选项卡筛选班级列表
const filteredClassList = computed(() => {
  if (activeKey.value === 'all') {
    return classList.value;
  } else {
    return classList.value.filter(item => item.status === activeKey.value);
  }
});

// 选项卡切换事件
const onTabChange = (key) => {
  console.log('切换到选项卡:', key);
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'ongoing': return '进行中';
    case 'finished': return '已结束';
    default: return '未知';
  }
};

// 获取状态颜色
const getStatusColor = (status) => {
  switch (status) {
    case 'ongoing': return 'green';
    case 'finished': return 'red';
    default: return 'default';
  }
};

// 显示创建班级模态框
const showCreateClassModal = () => {
  createClassModalVisible.value = true;
};

// 处理创建班级
const handleCreateClass = async () => {
  if (!createClassForm.name) {
    message.warning('请填写班级名称');
    return;
  }
  
  try {
    // 调用后端API创建班级
    const result = await createClass(createClassForm.name);
    
    if (result.code === 1) {
      message.success('班级创建成功');
      
      // 重置表单并关闭模态框
      createClassForm.name = '';
      createClassForm.description = '';
      createClassModalVisible.value = false;
      
      // 重新获取班级列表
      await fetchClassList();
    } else {
      message.error(result.msg || '班级创建失败');
    }
  } catch (error) {
    console.error('创建班级失败:', error);
    message.error('班级创建失败，请稍后重试');
  }
};

// 取消创建班级
const handleCancelCreateClass = () => {
  createClassModalVisible.value = false;
  createClassForm.name = '';
  createClassForm.description = '';
};

// 进入班级 - 在新标签页打开班级管理页面
const enterClass = (classId) => {
  console.log('进入班级，ID:', classId);
  // 构建班级管理页面的URL
  const url = `/class/${classId}`;
  // 在当前标签页中打开
  window.location.href = url;
};

// 复制邀请码
const copyInviteCode = (code) => {
  navigator.clipboard.writeText(code).then(() => {
    message.success('邀请码已复制到剪贴板');
  });
};
</script>

<style scoped>
.class-management-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.class-card {
  height: 100%;
}

.class-name {
  font-weight: bold;
  font-size: 16px;
}

.class-info {
  margin-bottom: 8px;
}

.label {
  font-weight: bold;
}

.invite-code {
  font-family: monospace;
  background-color: #f0f0f0;
  padding: 2px 4px;
  border-radius: 4px;
}
</style>